package com.atguigu.tingshu.user.strategy;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component("1003")
public class VipStrategy implements ItemTypeStrategy{
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        UserVipService userVipService = new UserVipService();
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        //获取购买vip的时长
        Long vipId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipId);
        //购买时长
        Integer vipMonth = vipServiceConfig.getServiceMonth();
        //获取用户信息
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        Date expireTime = new Date();
        //判断用户身份

        if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(new Date())){
            //如果是vip用户续期时间是vip的过期时间加购买时间
            LocalDateTime localDateTime = new LocalDateTime(userInfo.getVipExpireTime());
            expireTime= localDateTime.plusMonths(vipMonth).toDate();
        }
        else {
            //新开通或者已过期的用户的过期时间默认为当前时间加购买时间

            expireTime= new LocalDateTime().plusMonths(vipMonth).toDate();
        }
        userVipService.setExpireTime(expireTime);
        userVipService.setStartTime(new Date());
        userVipServiceMapper.insert(userVipService);
        //对新vip用户的属性进行修改
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(expireTime);
        userInfoMapper.updateById(userInfo);
    }
}
